package com.kongge.viewdisplayframeworklib;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.res.Configuration;
import android.os.Bundle;
import android.util.AttributeSet;
import android.view.KeyEvent;

import com.kongge.viewdisplayframeworklib.control.GlobalMagager;
import com.kongge.viewdisplayframeworklib.control.PublicInterface;
import com.kongge.viewdisplayframeworklib.control.TabControl;
import com.kongge.viewdisplayframeworklib.event.action.EQAction;
import com.kongge.viewdisplayframeworklib.landscape.AbstractUIManager;
import com.kongge.viewdisplayframeworklib.landscape.ActivityLifePriod;
import com.kongge.viewdisplayframeworklib.landscape.ActivityProtocal;
import com.kongge.viewdisplayframeworklib.landscape.EQScreenManager;
import com.kongge.viewdisplayframeworklib.landscape.LandscapeActivity;
import com.kongge.viewdisplayframeworklib.model.AbsUIController;
import com.kongge.viewdisplayframeworklib.model.ImageIdFactory;
import com.kongge.viewdisplayframeworklib.model.RuntimeManager;
import com.kongge.viewdisplayframeworklib.model.TabberBarItem;
import com.kongge.viewdisplayframeworklib.util.EQConstans;
import com.kongge.viewdisplayframeworklib.view.TabHexinView;

import java.io.Serializable;

/**
 * Created by kongge on 2017/11/17.
 * description:
 * layoutid:
 */
public class HexinMainView extends TabHexinView {

    private ActivityLifePriod mActivityState = new ActivityLifePriod();
    private boolean isAppExiting;
    private TabControl tabControl;

    public HexinMainView(Context context) {
        super(context);
    }

    public HexinMainView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        String configPath = PublicInterface.getConfigFilePath();
        init(configPath);
        PublicInterface.gotoTabbarSection(0);
    }

    @Override
    public void onDestroy() {
        // TODO Auto-generated method stub
        PublicInterface.onDestory();
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        // TODO Auto-generated method stub
        if (PublicInterface.onKeyDown(keyCode, event)) {
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    private void init(String configPath) {
        // TODO Auto-generated method stub
        PublicInterface.setGlobalActivity((Activity) getContext());
        PublicInterface.initGlabaManager(configPath);
        setTabControl();
        PublicInterface.setNavigateBar(mNavigateBar);
        PublicInterface.setParentViewGroup(pageContent);
        PublicInterface.setTabWidget(tabCtrl);

        for (int i = 0; i < PublicInterface.getTabbarItemCount(); i++) {
            TabberBarItem item = PublicInterface.getTabberBarItemByIndex(i);
            if (item != null) {
                tabCtrl.addSubTab(item.mName, getResources().getDrawable(ImageIdFactory.getImageResourceIdForName(item.mImage)));
            }
        }
    }

    public void onTabBarClick(int oldIndex, int newIndex) {
        PublicInterface.gotoTabbarSection(newIndex);
    }

    private void setTabControl() {
        if (tabControl == null) {
            AbstractUIManager uiManager = GlobalMagager.getTabControl();
            if (uiManager != null && uiManager instanceof TabControl) {
                tabControl = (TabControl) uiManager;

            }
        }
        GlobalMagager.setTabControl(tabControl);
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        // TODO Auto-generated method stub
        super.onConfigurationChanged(newConfig);
        if (mActivityState.isWaitingForResult || mActivityState.isOnBackgroup() || isAppExiting) {
            return;
        }
        if (mActivityState.isWaitingForResult || mActivityState.isOnBackgroup()) {
            return;
        }
        onChangeToLandscape();
    }

    private void onChangeToLandscape() {
        AbsUIController focusPage = tabControl.getCurPageControl();
        if (focusPage == null) {
            return;
        }
        int portraitFrameId = focusPage.getPageId();
        int landFrameId = EQScreenManager.getScreenMappingPage(portraitFrameId, ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
        // 判断是否有横屏
        if (landFrameId != EQConstans.INVALID_ID) {
            mActivityState.isWaitingForResult = true;
            Serializable info = focusPage.getInfo();

            // 通知转屏并且保存页面数据，需要保存的数据必须实现ISavePageState接口
            if (focusPage != null) {
                focusPage.broadcastScreenChange();
            }

            // 在切换到横屏的时候，记录下当前的状态
            GlobalMagager.setStartLandscapeActivity(true);

            // 启动横屏处理
            Intent intent = new Intent();
            intent.setClass(getContext(), LandscapeActivity.class);
            intent.setFlags(Intent.FLAG_ACTIVITY_NO_USER_ACTION);
            Bundle bundle = new Bundle();
            bundle.putInt(ActivityProtocal.KEY_PARAM_PORTRAIT_FRAMEID, landFrameId);
            bundle.putSerializable(ActivityProtocal.KEY_PARAM_SERIALIZABLE, info);
            intent.putExtras(bundle);
            intent.setFlags(Intent.FLAG_ACTIVITY_NO_USER_ACTION);
            ((Activity)getContext()).startActivityForResult(intent, ActivityProtocal.REQUEST_CODE_LANDSCAPE);

        } else {
            ((Activity)getContext()).setRequestedOrientation(Configuration.ORIENTATION_PORTRAIT);
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        // TODO Auto-generated method stub
        GlobalMagager.SetGlabalActivity((Activity) getContext());
        setTabControl();
        mActivityState.isWaitingForResult = false;
        if (requestCode == ActivityProtocal.REQUEST_CODE_LANDSCAPE && data != null) {
            Bundle landscapeParam = data.getExtras();
            if (landscapeParam != null) {
                RuntimeManager runtimeManager = GlobalMagager.getRuntimeManager();
                EQAction action = runtimeManager.getAction();
                PublicInterface.gotoPageWithPageId(action);
            }
        }

    }

    @Override
    public void onStart() {
        // TODO Auto-generated method stub
        mActivityState.mState = ActivityLifePriod.ACTIVITY_STATE_START;
    }

    @Override
    public void onRestart() {
        // TODO Auto-generated method stub
        mActivityState.mState = ActivityLifePriod.ACTIVITY_STATE_RESTART;
    }

    @Override
    public void onResume() {
        // TODO Auto-generated method stub
        mActivityState.mState = ActivityLifePriod.ACTIVITY_STATE_RESUME;
        if (tabControl != null) {
            tabControl.onActivityResume();
        }
    }

    @Override
    public void onPause() {
        // TODO Auto-generated method stub
        mActivityState.mState = ActivityLifePriod.ACTIVITY_STATE_PAUSE;
        if (tabControl != null) {
            tabControl.onActivityPause();
        }
    }

    @Override
    public void onStop() {
        // TODO Auto-generated method stub
        mActivityState.mState = ActivityLifePriod.ACTIVITY_STATE_STOP;
    }

    @Override
    public void onScreenConfigurationChanged(Configuration newConfig) {
        if (mActivityState.isWaitingForResult || mActivityState.isOnBackgroup() || isAppExiting) {
            return;
        }
        if (mActivityState.isWaitingForResult || mActivityState.isOnBackgroup()) {
            return;
        }
        onChangeToLandscape();
    }
}
